package com.liu.demo.service.impl;

import com.liu.demo.exception.REnum;
import com.liu.demo.exception.RException;
import com.liu.demo.pojo.Student;
import com.liu.demo.prository.StudnetPrository;
import com.liu.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentImplService implements StudentService {
    @Autowired
    private StudnetPrository studnetPrository;

    public List<Student> findAll(){
        return studnetPrository.findAll();
    }

    public List<Student> findByName(String name) {
        return studnetPrository.findByNameLike(name);
    }

    //按id查找
    public Student findByIdLike(Integer id) {
        return studnetPrository.findByIdLike(id);
    }

    //增加信息
    public void insertOne(Student student){
        studnetPrository.save(student);
    }

    //更新信息
    public void updateOne(Student student){
        studnetPrository.save(student);
    }

    //删除信息
    public void deleteOne(Student student){
        studnetPrository.delete(student);
    }

    //只支持分页的查询
    public Page<Student> findAll(Pageable pageable){
        return studnetPrository.findAll(pageable);
    }

    //分页按照给定例子查询
    public Page<Student> findAll(Example<Student> student, Pageable pageable){
        return studnetPrository.findAll(student,pageable);
    }

    //按照名字和学号查找
    public Student findByNameAndId(String name,Integer id) throws Exception{
        List<Student> findRes = studnetPrository. findByNameAndId(name,id);

        if(findRes.size() > 0){
            return findRes.get(0);
        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}
